package ar.edu.utn.frsf.tpae.a2012.g03.interfaz.controller;


import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import ar.edu.utn.frsf.tpae.a2012.g03.interfaz.util.ServiceLocator;
import ar.edu.utn.frsf.tpae.a2012.g03.logica.PagoLogica;
import ar.edu.utn.frsf.tpae.a2012.g03.model.Movimiento;

/**
 * 
 * @author marianof
 * Back bean para la pagina listaMovimientos.jsp
 */
public class MovimientoBean {

	private List<Movimiento> movimientos;

	
	@PostConstruct
	public void init() {
		try {
		PagoLogica pago = ServiceLocator.getPagoLogica();
		//movimientos = pago.;
		Integer cuentaId = Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"));
		movimientos = pago.getPagos(cuentaId);
		} catch(Exception ex) {
			movimientos = new ArrayList<>();
		}
	}


	public List<Movimiento> getMovimientos() {
		return movimientos;
	}


	public void setMovimientos(List<Movimiento> movimientos) {
		this.movimientos = movimientos;
	}
	
	public void downloadFile() throws Exception {

	    try {

	        String filename = "analysis.csv";

	        FacesContext fc = FacesContext.getCurrentInstance();
	        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

	        response.reset();
	        response.setContentType("text/comma-separated-values");
	        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

	        OutputStream output = response.getOutputStream();

	        // writing just sample data
	        List<String> strings = new ArrayList<String>();

	        strings.add("filename" + ";" + "description" + "\n");
	        strings.add(filename + ";" + "this is just a test" + "\n");

	        for (String s : strings) {
	            output.write(s.getBytes());
	        }

	        output.flush();
	        output.close();

	        fc.responseComplete();

	    } catch (IOException e) {
	        throw new Exception("an error occurred");
	    }
	}
	
	
}
